package edu.dut.personal_scheduler.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import edu.dut.personal_scheduler.R;
import edu.dut.personal_scheduler.utils.Encrypter;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginFragment extends AbsFragment {

	private EditText usernameEt, passwordEt;
	private Button loginBtn, registerBtn;
	private ProgressDialog waitDialog;

	private Handler uiHandler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragement_login, null);
		usernameEt = (EditText) view.findViewById(R.id.editText_loginName);
		passwordEt = (EditText) view.findViewById(R.id.editText_loginPwd);
		loginBtn = (Button) view.findViewById(R.id.button_loginDo);
		registerBtn = (Button) view.findViewById(R.id.button_loginReg);

		waitDialog = new ProgressDialog(getActivity());
		waitDialog.setMessage("Please Wait");

		loginBtn.setOnClickListener(new LoginActionListener());
		registerBtn.setOnClickListener(new RegisterActionListener());

		uiHandler = new Handler(Looper.getMainLooper()) {
			@Override
			public void handleMessage(Message msg) {
				waitDialog.dismiss();
				String toastContent = "";
				switch (msg.what) {
				case 0:
					toastContent = "登录成功";
					break;
				case 1:
					toastContent = "错误的用户名或密码";
					break;
				case -1:
					toastContent = "网络异常，请重试";
					break;
				}
				Toast.makeText(getActivity(), toastContent, Toast.LENGTH_SHORT).show();
			}
		};
		return view;
	}

	class RegisterActionListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			startFragent(new RegisterFragment(), true);
		}

	}

	class LoginActionListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (getInputStatus()) {
				hideOrShowInput();
			}
			if ("".equals(usernameEt.getText().toString())) {
				Toast.makeText(getActivity(), "账号不能为空", Toast.LENGTH_SHORT).show();
			} else if ("".equals(passwordEt.getText().toString())) {
				Toast.makeText(getActivity(), "密码不能为空", Toast.LENGTH_SHORT).show();
			} else {
				waitDialog.show();
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							//GET"http://pswsr.jd-app.com/hello?type=Login&login_usrname=Admin-1623"
							HttpPost httpRequest = new HttpPost("http://pswsr.jd-app.com/hello");
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							params.add(new BasicNameValuePair("type", "Login"));
							//params.add(new BasicNameValuePair("login_usrname", "Admin-1623"));
							params.add(new BasicNameValuePair("login_usrname", usernameEt.getText().toString()));
							//String encryptedPassword = Encrypter.SHA1("qazwsx123");
							String encryptedPassword = Encrypter.SHA1(passwordEt.getText().toString());
							params.add(new BasicNameValuePair("login_password", encryptedPassword));
							httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

							HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

							if (httpResponse.getStatusLine().getStatusCode() == 200) {
								final HttpEntity entity = httpResponse.getEntity();
								String resStr = EntityUtils.toString(entity);
								if (resStr.equals("Login_Success")) {
									uiHandler.sendEmptyMessage(0);
								} else if (resStr.equals("Login_WrongPwd")) {
									uiHandler.sendEmptyMessage(1);
								} else {
									uiHandler.sendEmptyMessage(-1);
								}
							} else {
								uiHandler.sendEmptyMessage(-1);
							}
						} catch (Exception e) {
							uiHandler.sendEmptyMessage(-1);
						}
					}
				}).start();
			}
		}
	}

	@Override
	public String getPageTitle() {
		return "登录";
	}
}
